//
//  RelatedProductsViewController.swift
//  月升
//
//  Created by 拉利法 on 2024/7/10.
//  相关产品

import UIKit
import AVKit
import GKPhotoBrowser

class RelatedProductsViewController: QIBaseViewController {
    
    var resultModel = QISkinAnalysisResultsModel()
    var index = 0
    lazy var player = AVPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "相关产品"
        
        addUI()
    }
    

    
    private func addUI() {
        showGradientColor()
        
        let videoView = UIView()
        videoView.frame = CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: 222)
        videoView.backgroundColor = RandomColor()
        view.addSubview(videoView)
        
        var videoUrl = ""
        if index == 0 {
            videoUrl = resultModel.acne_video
        } else if index == 1 {
            videoUrl = resultModel.pore_video
        } else if index == 2 {
            videoUrl = resultModel.wrinkle_video
        }
        //"http://21live.62.hzgqapp.com/uploads/20240701/451c85702420ca0af669c8c81e32bca9.mp4"
        if videoUrl.count > 0 {
            let videoURL = URL(string: videoUrl)
            player = AVPlayer(url: videoURL!)
        }
        
        
        let playerLayer = AVPlayerLayer.init(player: player)
        playerLayer.frame = videoView.bounds
        playerLayer.backgroundColor = UIColor.black.cgColor
        playerLayer.videoGravity = .resizeAspect//AVLayerVideoGravityResizeAspect
        playerLayer.contentsScale = UIScreen.main.scale
        videoView.layer.addSublayer(playerLayer)
        player.play()
        
        
        let videoBtn = UIButton().then {
            $0.frame = videoView.bounds
            $0.setImage(UIImage(named: "暂停播放"), for: .selected)
            $0.addTarget(self, action: #selector(videoBtnClick(btn: )), for: .touchUpInside)
        }
        videoView.addSubview(videoBtn)
        
        view.addSubview(collectionView)
        
    }
    
    @objc private func videoBtnClick(btn: UIButton) {
        btn.isSelected = !btn.isSelected
        if btn.isSelected {
            player.pause()
        } else {
            player.play()
        }
    }
    
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
//        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: NAV_HEIGHT + 230, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT - 230), collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.register(RelatedProductsViewCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        
        return collectionView
    }()
    
    deinit {
        print("RelatedProductsViewController释放")
    }
}


extension RelatedProductsViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let cellW = SCREEN_WIDTH / 2 - 6
        return CGSize(width: cellW, height: cellW * 0.94)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if index == 0 {
            return resultModel.acne.count
        } else if index == 1 {
            return resultModel.pores.count
        } else if index == 2 {
            return resultModel.wrinkles.count
        } else {
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RelatedProductsViewCell
        if index == 0 {
            cell.model = resultModel.acne[indexPath.row]
        } else if index == 1 {
            cell.model = resultModel.pores[indexPath.row]
        } else if index == 2 {
            cell.model = resultModel.wrinkles[indexPath.row]
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var model = QIProductInfoModel()
        if index == 0 {
            model = resultModel.acne[indexPath.row]
        } else if index == 1 {
            model = resultModel.pores[indexPath.row]
        } else if index == 2 {
            model = resultModel.wrinkles[indexPath.row]
        }
//        let alertCtl = UIAlertController(title: model.name, message: model.introduction, preferredStyle: .alert)
//        alertCtl.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
//            
//        }))
//        self.present(alertCtl, animated: true)
        
        let cell = collectionView.cellForItem(at: indexPath) as! RelatedProductsViewCell
        var photos = [GKPhoto]()
        let photo = GKPhoto()
        photo.image = cell.bgImgView.image
        photos.append(photo)
        
        
        let browser = GKPhotoBrowser(photos: photos, currentIndex: 0)
        browser.showStyle = .none
        browser.show(fromVC: self)
        
        let titlel = UILabel().then({
            $0.frame = CGRect(x: 10, y: SCREEN_HEIGHT - 100, width: SCREEN_WIDTH - 20, height: 100)
            $0.backgroundColor = UIColor(white: 0.1, alpha: 0.1)
            $0.text = model.name
            $0.numberOfLines = 0
            $0.textColor = .white
            $0.font = FONT(ofSize: 15)
        })
        browser.view.addSubview(titlel)
    }
}


class RelatedProductsViewCell: UICollectionViewCell {
    
    var bgImgView = UIImageView()
    private var titleL = UILabel()
    private var detailL = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        addUI()
    }
    
    private func addUI() {
        bgImgView = UIImageView().then {
            $0.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height)
            $0.image = UIImage(named: "noo")
            $0.contentMode = .scaleAspectFill
            $0.clipsToBounds = true
        }
        self.addSubview(bgImgView)
        
        titleL = UILabel().then({
            $0.frame = CGRect(x: 10, y: 110, width: self.width - 20, height: 20)
            $0.backgroundColor = UIColor(white: 0.1, alpha: 0.1)
            $0.text = "产品名/简介"
            $0.textColor = .white
            $0.font = FONTBOLD(ofSize: 14)
        })
        self.addSubview(titleL)
        
        detailL = UILabel().then({
            $0.frame = CGRect(x: 10, y: titleL.bottom, width: titleL.width, height: 34)
            $0.backgroundColor = UIColor(white: 0.1, alpha: 0.1)
            $0.text = "水淀粉红色的风景大死角的方式"
            $0.numberOfLines = 2
            $0.textColor = .white
            $0.font = FONT(ofSize: 12)
        })
        self.addSubview(detailL)
    }
    
    var model = QIProductInfoModel() {
        didSet {
            bgImgView.kf.setImage(with: URL(string: model.image_name), placeholder: UIImage(named: "noo"))
            titleL.text = model.name
            detailL.text = model.introduction
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
